<?php 
	require_once "./config/sys_config.php";
	require_once "./config/user_config.php";
	require_once MB_APP_DIR.'/common/exception.class.php';
	require_once MB_MODEL_DIR.'/api_client.class.php';
	require_once MB_VIEW_DIR.'/template_view.class.php';
	
	class GuestAPI{
		
		private $apiClient;
		
		public function __construct(){
			global $mbConfig;
			
			$randIndex = rand(0,count($mbConfig["mb_admin_access_token"])-1);
			
			$r_access_token = $mbConfig["mb_admin_access_token"][$randIndex]["mb_admin_oauth_token"];
			$r_access_token_secret = $mbConfig["mb_admin_access_token"][$randIndex]["mb_admin_oauth_token_secret"];
			
			$this->apiClient = new MBApiClient(MB_AKEY,MB_SKEY,$r_access_token,$r_access_token_secret);
		}
		
		/**
		 * 
		 * 返回广播大厅的实时数据，已格式化为基本的HTML
		 * 
		 * @var $num 广播大厅数据返回的条数
		 * @return HTML数据
		 */
		public function getPublicTimeLine( $num = 10 ){
			$timeline = $this->apiClient->getPublic(array("p"=>0,"n"=>$num));
			
			$templdateData = array();
			$templdateData["t"]=$timeline["data"]["info"];
			
			foreach( $templdateData["t"] as &$t){//格式化模版数据
				if(!empty($t["head"])){
					$t["head"] .= "/50";
				}
				unset($t["image"]);
				unset($t["source"]);
			}
			
			$html = TemplateView::renderView($templdateData,"/common/tbody.view.php");
			return $html;
		}
		
		/**
		 * 
		 * 根据传入的时间戳返回一条最新的广播大厅数据，已格式化为基本的HTML
		 * 不传入时间戳则取第一条数据
		 * 
		 * @var $sincetime 时间戳
		 * @return 最新一条广播的HTML数据
		 * 
		 */
		public function getPublicTimelineUpdate( $sincetime = 1 ){
			
			$sincetime = intval($sincetime);
			
			$timeline = $this->apiClient->getPublic(array("p"=>0));//首页
			
			$templdateData = array();
			$templdateData["t"] = array();
			
			foreach( $timeline["data"]["info"] as $t ){
				if( $t["timestamp"] > $sincetime || $sincetime == 1 ){
					
					if(!empty($t["head"])){
						$t["head"] .= "/50";
					}
					
					unset($t["image"]);
					unset($t["source"]);
					
					$templdateData["t"][] = $t;
					break;
				}
			}
			
			$html = TemplateView::renderView($templdateData,"/common/tbody.view.php");
			
			return $html;
		}
		
		/**
		 * 
		 * 取单个用户的腾讯微博资料
		 * @var $name 用户名
		 * @return Array用户资料
		 */
		
		public function getUserInfo( $name ){
			
			if(!isset($name)){
				return array();
			}
			
			$expectedCacheFileName = urlencode($name).".php";
			$expectedCacheFilePath = MB_ROOT_DIR."/cache/user/".$expectedCacheFileName;
			$expectedCacheFileExists = file_exists($expectedCacheFilePath);
			$expectedCacheFileNeedUpdate = $expectedCacheFileExists && ( filemtime($expectedCacheFilePath) < ( time() - 7200 ));//缓存文件自创建起每两小时更新
			
			if( !$expectedCacheFileExists || $expectedCacheFileNeedUpdate ){//生成缓存数据
				try{
					$userinfo = $this->apiClient->getUserInfo(array("n" => $name));
					if(!empty($userinfo["data"])){
						unset($userinfo["data"]["name"]);
						$cacheFileHandler = @fopen($expectedCacheFilePath,"w+");
						if($cacheFileHandler){//创建缓存文件成功
							$cacheFileContent = '<?php $cachedUserData = ' . var_export($userinfo["data"],true) . ';?>';
							fwrite($cacheFileHandler,$cacheFileContent);
							@fclose($cacheFileHandler);
						}
						return $userinfo["data"];
					}
					return array();
				}catch(Exception $e){
					return array();
				}
			}else{
				@include $expectedCacheFilePath;
				return $cachedUserData;
			}
		}

		/**
		 * 
		 * 批量取用户的腾讯微博资料
		 * 
		 * @var $name 腾讯微博用户名列表数组
		 * @return Array用户资料
		 */
		
		public function getUsersInfo( $names ){
			
			if(!isset($names)){
				return array();
			}
			
			$returnArr = array();
			foreach( $names as $name ){
				$userinfo = $this->getUserInfo($name);
				$returnArr[$name] = $userinfo;
			}
			
			return $returnArr;
		}
		
		/**
		 * 
		 * 获取最热话题
		 * 
		 * @var $topicnames 话题名
		 * @var $num 数量
		 * @return Array 热门话题
		 */
		public function getHotTopic( $topicnames,$num = 10 ){
			try{
				if( isset($topicnames) && is_array($topicnames) && !empty($topicnames) ){//构造相同的数据结构
					$hottopics=array(
						"data"=>array(
							"info"=>array(
							)
						)
					);
					
					for( $i=0; $i<$num; $i++ ){//最多num条
						if(!array_key_exists($i,$topicnames)){
							break;
						}
						$topicname = $topicnames[$i];
						$hottopics["data"]["info"][] = array("name"=>$topicname);
					};
					
				}else{
					$hottopics = $this->apiClient->getHotTopic(array("type" => 2,"n"=>$num,"pos"=>0));
				}
				if(!empty($hottopics["data"]["info"])){
					//取话题名字
					$nocacheTopicNameArr = array();
					$topicNames = array();
					
					foreach( $hottopics["data"]["info"] as $hottopic ){
						$topicNames[] = $hottopic["name"];
						$cacheFilePath = MB_ROOT_DIR."/cache/topic/".urlencode($hottopic["name"]).".php";
						if(!file_exists($cacheFilePath) || ( file_exists($cacheFilePath) && (filemtime($cacheFilePath) < ( time() - 7200) ) ) ){//无缓存或缓存需更新，放入拉数据的队列
							$nocacheTopicNameArr[] = $hottopic["name"];
						}
					}
					
					if( count($nocacheTopicNameArr) > 0 ){
							//取没有缓存过的话题id
							$nocacheHotTopicIds = $this->apiClient->getTopicId(array("list"=>implode(",",$nocacheTopicNameArr)));
							
							//取没有缓存过的话题详细信息
							if(isset($nocacheHotTopicIds) && !empty($nocacheHotTopicIds["data"]["info"])){
								$nocacheTopicIdArr = array();
								foreach($nocacheHotTopicIds["data"]["info"] as $tempinfo){
									if( $tempinfo["id"] != 0 ){//有效话题id不为0
										$nocacheTopicIdArr[] = $tempinfo["id"];
									}else{//写入话题id为0即无效话题的缓存
										$topicCachePath = MB_ROOT_DIR."/cache/topic/".urlencode($tempinfo["text"]).".php";
										$topicCacheFileHandler = @fopen($topicCachePath,"w+");
										if($topicCacheFileHandler){
											$topicCacheFileContent = '<?php $cachedData='.var_export($tempinfo,true)."; ?>";
											fwrite($topicCacheFileHandler,$topicCacheFileContent);
											@fclose($topicCacheFileHandler);
										}
									}
								}
								if(!empty($nocacheTopicIdArr)){
									//终于可以取完整的话题信息了
									$noCacheHotTopicInfo = $this->apiClient->getTopicList(array("list"=>implode(",",$nocacheTopicIdArr)));
									if(isset($noCacheHotTopicInfo) && !empty($noCacheHotTopicInfo["data"]["info"])){
										foreach($noCacheHotTopicInfo["data"]["info"] as $nocacheinfo){
											$topicCachePath = MB_ROOT_DIR."/cache/topic/".urlencode($nocacheinfo["text"]).".php";
											$topicCacheFileHandler = @fopen($topicCachePath,"w+");
											if($topicCacheFileHandler){
												$topicCacheFileContent = '<?php $cachedData='.var_export($nocacheinfo,true)."; ?>";
												fwrite($topicCacheFileHandler,$topicCacheFileContent);
												@fclose($topicCacheFileHandler);
											}
										}
									}
								}//end $nocacheTopicIdArr
							}
					 }//end $nocacheTopicNameArr > 0
					 
					 $returnArr = array();
					 foreach($topicNames as $topicname){
					 	@include MB_ROOT_DIR."/cache/topic/".urlencode($topicname).".php";
					 	$returnArr[] = $cachedData;
					 }
					 return $returnArr;
				}
			}catch(Exception $e){
				return array();
			}
			return array();
		}
		
		/**
		 * 
		 * 返回登录页的同城广播，已格式化为基本的HTML
		 * 
		 * @var $num 登录页同城广播返回的条数
		 * @return HTML数据
		 */
		public function getCityBroadcast( $kw = "", $num = 10 ){
			$param = array(
				'k'=>$kw,
				'n'=>$num,
				'p'=>1,
				'type' => 1	
			);
			$timeline = $this->apiClient->getSearch($param);
			
			$templdateData = array();
			$templdateData["t"]=$timeline["data"]["info"];
			
			foreach( $templdateData["t"] as &$t){//格式化模版数据
				if(!empty($t["head"])){
					$t["head"] .= "/50";
				}
				unset($t["image"]);
				unset($t["source"]);
			}
			$html = TemplateView::renderView($templdateData,"/login/tbody.view.php");
			return $html;
		}
	}
?>